use bracket_lib::prelude::*;
use image::*;

use crate::{player::Player, SCREEN_HEIGHT};
/// gap_y - (size/2)
/// gap_y
/// gap_y + (size/2)
pub struct Obstacle {
    pub x: i32,     // 整个世界空间的横坐标
    pub gap_y: i32, // 中间的空隙坐标
    pub size: i32,  // 空隙大小
    pub img: DynamicImage, // 新增图片字段，设为pub
    pub shape_type: i32, // 障碍物形状类型：0=标准，1=上宽下窄，2=上窄下宽，3=中间宽
    pub shape_factor: f32, // 形状变化因子
}

impl Obstacle {
    pub fn new(x: i32, _score: i32) -> Self {
        let mut random = RandomNumberGenerator::new();
        let size = random.range(10, (SCREEN_HEIGHT * 2) / 3); // 可通过范围最小10，最大2/3屏幕宽度
        let half_size = size / 2;
        let min_gap_y = half_size + 2;
        let max_gap_y = SCREEN_HEIGHT - half_size - 2;
        let gap_y = random.range(min_gap_y, max_gap_y);   // 不包含max_gap_y
        Obstacle {
            x,
            gap_y,
            size,
            img: image::open("assets/obstacle.png").unwrap(), // 加载图片
            shape_type: random.range(0, 4), // 随机形状类型
            shape_factor: random.range(50, 150) as f32 / 100.0, // 随机形状因子 0.5-1.5
        }
    }
    // 渲染障碍物
    pub fn render(&mut self, ctx: &mut BTerm, player_x: i32) {
        let screen_x = self.x - player_x; // 屏幕上的空间
        let _half_size = self.size / 2; // 未使用，添加下划线前缀
        let (img_width, img_height) = self.img.dimensions();
        
        // 扩展到5像素宽度以更好地显示图片
        for dx in 0..5 {
            let obstacle_x = screen_x + dx;
            if obstacle_x >= 0 && obstacle_x < 120 {
                // 根据形状类型计算当前x位置的有效空隙大小
                let effective_size = self.get_effective_size_at_x(dx);
                let effective_half_size = effective_size / 2;

                // 上边的障碍物
                for y in 0..self.gap_y - effective_half_size {
                    let img_x = (dx as f32 / 5.0 * img_width as f32) as u32;
                    let img_y = (y as f32 / (self.gap_y - effective_half_size) as f32 * img_height as f32) as u32;
                    
                    // 确保不超出图片边界
                    let img_x = img_x.min(img_width - 1);
                    let img_y = img_y.min(img_height - 1);
                    
                    let pixel = self.img.get_pixel(img_x, img_y);
                    ctx.set_bg(obstacle_x, y, (pixel[0], pixel[1], pixel[2]));
        }
                
                // 下边的障碍物
                for y in self.gap_y + effective_half_size..SCREEN_HEIGHT {
                    let img_x = (dx as f32 / 5.0 * img_width as f32) as u32;
                    let img_y = ((y - (self.gap_y + effective_half_size)) as f32 / (SCREEN_HEIGHT - (self.gap_y + effective_half_size)) as f32 * img_height as f32) as u32;
                    
                    // 确保不超出图片边界
                    let img_x = img_x.min(img_width - 1);
                    let img_y = img_y.min(img_height - 1);
                    
                    let pixel = self.img.get_pixel(img_x, img_y);
                    ctx.set_bg(obstacle_x, y, (pixel[0], pixel[1], pixel[2]));
                }
            }
        }
    }
    
    // 根据x位置计算有效空隙大小
    fn get_effective_size_at_x(&self, dx: i32) -> i32 {
        let base_size = self.size as f32;
        let x_ratio = dx as f32 / 4.0; // 0.0 到 1.0
        
        match self.shape_type {
            0 => self.size, // 标准形状
            1 => { // 上宽下窄
                let factor = 1.0 + (1.0 - x_ratio) * self.shape_factor;
                (base_size * factor) as i32
            },
            2 => { // 上窄下宽
                let factor = 1.0 + x_ratio * self.shape_factor;
                (base_size * factor) as i32
            },
            3 => { // 中间宽
                let factor = 1.0 + (1.0 - (x_ratio - 0.5).abs() * 2.0) * self.shape_factor;
                (base_size * factor) as i32
            },
            _ => self.size,
        }
    }
    /// 判断是否撞到（只有玩家中心3x3区域碰撞才算失败）
    pub fn hit_obstacle(&self, player: &Player) -> bool {
        // 计算玩家中心3x3区域的边界（玩家是6x6，中心3x3从偏移1.5开始）
        let player_center_left = player.x + 1;
        let player_center_right = player.x + 3; // 1+2=3
        let player_center_top = player.y + 1;
        let player_center_bottom = player.y + 3;
        
        // 计算障碍物的边界（5像素宽度）
        let obstacle_left = self.x;
        let obstacle_right = self.x + 4; // 5像素宽度
        
        // 检查x轴是否有重叠
        let x_overlap = player_center_left <= obstacle_right && player_center_right >= obstacle_left;
        
        if x_overlap {
            // 计算玩家在障碍物中的相对x位置，确保在有效范围内
            let relative_x = (player_center_left - obstacle_left).max(0).min(4);
            let effective_size = self.get_effective_size_at_x(relative_x);
            let effective_half_size = effective_size / 2;
            
            // 确保有效空隙大小合理
            let safe_half_size = effective_half_size.max(1);
            
            // 计算空隙的上下边界
            let gap_top = self.gap_y - safe_half_size;
            let gap_bottom = self.gap_y + safe_half_size;
            
            // 检查玩家是否完全在空隙内
            let player_in_gap = player_center_top >= gap_top && player_center_bottom <= gap_bottom;
            
            // 如果玩家不在空隙内，则发生碰撞
            return !player_in_gap;
        }
        
        false
    }
}